#include <webx/menu.h>
#include <dbentity/T_XG_MENU.h>
#include <dbentity/T_XG_GROUP.h>

class GetMenuContent : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetMenuContent)

int GetMenuContent::process()
{
	param_string(id);
	
	webx::CheckAlnumString(id);

	string sqlcmd;
	sp<DBConnect> dbconn = webx::GetDBConnect();

	if (id == "QUERYGROUP")
	{
		sqlcmd = "SELECT ID,URL,ICON,TITLE,ENABLED,STATETIME FROM T_XG_MENU LIMIT 1";
	}
	else
	{
		sqlcmd = stdx::format("SELECT ID,URL,ICON,TITLE,ENABLED,STATETIME FROM T_XG_MENU WHERE ID='%s'", id.c_str());
	}
	
	int res = 0;
	sp<RowData> row;
	sp<QueryResult> rs = dbconn->query(sqlcmd);

	if (!rs) return simpleResponse(XG_SYSERR);

	while (row = rs->next())
	{
		json["id"] = row->getString(0);
		json["url"] = row->getString(1);
		json["icon"] = row->getString(2);
		json["title"] = row->getString(3);
		json["enabled"] = row->getString(4);
		json["statetime"] = row->getString(5);
	}
	
	sqlcmd = "SELECT ID,NAME,ICON,ENABLED,MENULIST FROM T_XG_GROUP ORDER BY ID";

	if (!(rs = dbconn->query(sqlcmd))) return simpleResponse(XG_SYSERR);

	string tag = "," + id + ",";
	
	while (row = rs->next())
	{
		string grp = "," + row->getString(4) + ",";
		JsonElement item = json["grouplist"][res++];

		item["id"] = row->getString(0);
		item["name"] = row->getString(1);
		item["icon"] = row->getString(2);
		item["enabled"] = row->getString(3);
		item["checked"] = (grp.find(tag) != string::npos);
	}

	json["code"] = res;
	out << json;
	
	return XG_OK;
}